<template>
  <div v-show="getShow">
    <h2 class="register-title">忘记密码</h2>
    <a-form
      ref="loginForm"
      :model="formState"
      :label-col="labelCol"
      style="width: 18rem; height: 300px"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        name="userName"
        :rules="[
          { required: true, message: '请输入用户名!' },
          { validator: isPhoneNumber, trigger: 'blur' },
        ]"
      >
        <a-input v-model:value="formState.userName" placeholder="请输入用户名" autocomplete="off">
          <template #prefix>
            <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item name="smsCode" :rules="[{ required: true, message: '请输入验证码!' }]">
        <a-input
          v-model:value="formState.smsCode"
          placeholder="验证码"
          autocomplete="off"
          style="width: 10rem"
        >
          <template #prefix>
            <MailOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input>
        <a-button
          :disabled="myState.smsSendFlag"
          v-text="(!myState.smsSendFlag && '获取验证码') || `${myState.time} s`"
          @click="getSms"
          style="margin-left: 15px; border-radius: 6px"
          type="primary"
        ></a-button>
      </a-form-item>

      <a-form-item
        name="userPassword"
        :rules="[{ validator: handlePasswordLevel }, { validator: handlePasswordLength }]"
      >
        <a-input-password
          v-model:value="formState.userPassword"
          type="password"
          placeholder="密码至少8位,区分大小写!"
          autocomplete="off"
          @focus="passwordLevelChecked = true"
          @blur="passwordLevelChecked = false"
        >
          <template #prefix>
            <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input-password>
      </a-form-item>

      <div
        style="position: absolute; right: 0px; bottom: 160px; z-index: 10"
        v-if="passwordLevelChecked"
      >
        <a-popover
          v-model:open="passwordLevelChecked"
          placement="right"
          v-if="passwordLevelChecked"
        >
          <template #content>
            <div style="display: flex; justify-content: space-between">
              <!-- <div></div> -->
              <div style="display: flex; align-items: center">
                <div :class="['user-register', passwordLevelClass]" style="margin-right: 10px">
                  <span>{{ passwordLevelName }}</span>
                </div>
                <a-progress
                  :percent="percent"
                  :steps="3"
                  :showInfo="false"
                  :strokeColor="passwordLevelColor"
                />
              </div>
            </div>
          </template>
        </a-popover>
      </div>
      <a-form-item
        name="confirmPassword"
        :rules="[
          { required: true, message: '请输入确认密码!' },
          { validator: passwordisEqual, trigger: 'blur' },
        ]"
      >
        <a-input-password
          v-model:value="formState.confirmPassword"
          type="password"
          placeholder="请输入确认密码"
          autocomplete="off"
        >
          <template #prefix>
            <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item style="text-align: left">
        <a-button style="width: 6rem; border-radius: 6px" type="primary" block html-type="submit">
          重置密码
        </a-button>
        <a-button type="link" @click="userLoginValue = 0">返回登录页面</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/modules/user'
import * as userApi from '@/api/user'
import { message } from 'ant-design-vue'
import { reactive, ref, computed } from 'vue'
const userStore = useUserStore()

const { userLoginValue } = storeToRefs(userStore)
const getShow = computed(() => {
  return 'fotget'
})
const router = useRouter()
const myState = reactive({
  smsSendFlag: false,
  time: 60,
})

const levelNames = ref({
  0: '低',
  1: '低',
  2: '中',
  3: '强',
})
const levelClass = ref({
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success',
})
const levelColor = ref({
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#1890ff',
})
const passwordLevel = ref(0)
const passwordLevelChecked = ref(false)
const percent = ref(10)
const progressColor = ref('#FF0000')
// 获取验证码
const getSms = async () => {
  loginForm.value?.validateFields(['userName']).then(async () => {
    let params = {
      phone: formState.value.userName,
    }
    if (params['phone'] == '') {
      message.error(`用户名不能为空~`)
      return
    }

    const hide = message.loading('验证码发送中..', 0)
    try {
      let { state, message: msg } = await userApi.sendRegSms(params)
      if (state === 200) {
        myState.smsSendFlag = true
        const interval = setInterval(() => {
          if (myState.time-- <= 0) {
            myState.time = 60
            myState.smsSendFlag = false
            clearInterval(interval)
          }
        }, 1000)
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    setTimeout(hide, 1)
  })
}

let labelCol = { span: 4 }
let loginForm = ref<HTMLElement | null>(null)
interface formState {
  userName: string | number
  userPassword: string
  confirmPassword: string
  smsCode: string | number
}
const formState = ref<formState>({
  userName: '',
  userPassword: '',
  confirmPassword: '',
  smsCode: '',
})

// 重置密码
const handleSubmit = async () => {
  const params: formState = {
    userName: formState.value.userName,
    smsCode: formState.value.smsCode,
    userPassword: formState.value.userPassword,
    confirmPassword: formState.value.confirmPassword,
  }
  let key: keyof formState
  for (key in params) {
    if (params[key] == '') {
      switch (key) {
        case 'userName':
          message.error(`用户名不能为空~`)
          return
        case 'smsCode':
          message.error(`验证码不能为空~`)
          return
        case 'userPassword':
          message.error(`密码不能为空~`)
          return
        case 'confirmPassword':
          message.error(`确认密码不能为空~`)
          return
      }
    }
  }
  try {
    const { state, message: msg } = await userApi.resetPassword(params)
    if (state === 200) {
      message.success('密码修改成功~')
      goLogin()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 返回登陆
const goLogin = () => {
  router.push({ path: '/login' })
}
const onFinish = async (values: any) => {
  const params: formState = {
    userName: formState.value.userName,
    smsCode: formState.value.smsCode,
    userPassword: formState.value.userPassword,
    confirmPassword: formState.value.confirmPassword,
  }
  try {
    const { state, message: msg } = await userApi.resetPassword(params)
    if (state === 200) {
      message.success('密码修改成功~')
      goLogin()
      let params = {
        userName: formState.value.userName,
        password: formState.value.userPassword,
      }
      await userStore.login(params)
      router.push({ path: '/' })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}
//验证手机号 是否正常
const isPhoneNumber = (rule: any, value: any, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 假设这是中国的手机号格式
  const numberGex = /^[0-9]+$/
  if (isNaN(value)) {
    callback(new Error('请输入有效的用户名！'))
  }
  if (!phoneRegex.test(value) && value && numberGex.test(value)) {
    callback(new Error('请输入有效的用户名！'))
  } else {
    callback()
  }
}
//两次密码输入是否一致
const passwordisEqual = (rule: any, value: any, callback: any) => {
  if (formState.value.userPassword !== value && formState.value.userPassword && value) {
    callback(new Error('两次输入的密码不一致！'))
  } else {
    callback()
  }
}
const passwordLevelClass = computed(() => {
  return levelClass.value[passwordLevel.value]
})
const passwordLevelName = computed(() => {
  return levelNames.value[passwordLevel.value]
})
const passwordLevelColor = computed(() => {
  return levelColor.value[passwordLevel.value]
})
const handlePasswordLevel = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback()

    // return
  }
  let level = 0

  // 判断这个字符串中有没有数字
  if (/[0-9]/.test(value)) {
    level++
  }
  // 判断字符串中有没有字母
  if (/[a-zA-Z]/.test(value)) {
    level++
  }
  // 判断字符串中有没有特殊符号
  if (/[^0-9a-zA-Z_]/.test(value)) {
    level++
  }
  passwordLevel.value = level
  percent.value = level * 30
  if (level >= 2) {
    if (level >= 3) {
      percent.value = 100
    }
    callback()
  } else {
    if (level === 0) {
      percent.value = 10
    }
    callback(new Error('密码强度不够!'))
  }
}
const handlePasswordLength = (rule: any, value: any, callback: any) => {
  if (value.length < 8 && value) {
    callback(new Error('密码至少8位,包含字母数字符号!'))
  } else if (!value) {
    callback(new Error('密码至少8位,包含字母数字符号!'))
  } else {
    callback()
  }
}
</script>

<style lang="less" scoped>
.register-title {
  margin-bottom: 30px;
  font-size: 18px;
}

.register-form {
  max-width: 400px;
  background-color: #fff;
  overflow: hidden;

  .register-form-button {
    margin-right: 15px;
  }
}
</style>
